package org.example.mall.admin.service.manage.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.example.mall.admin.constant.auth.enums.ClientEnum;
import org.example.mall.admin.mapper.manage.RoleMapper;
import org.example.mall.admin.model.dto.manage.RoleMenuDto;
import org.example.mall.admin.model.entity.manage.Role;
import org.example.mall.admin.model.enums.manage.SysRelationEnum;
import org.example.mall.admin.service.manage.RoleService;
import org.example.mall.admin.service.manage.SysRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author hzq
 * @since 2021-12-29
 */
@Service
@AllArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final SysRelationService sysRelationService;

    @Override
    public List<Role> accountRoles(Integer accountId, String clientId) {
        return getBaseMapper().accountRoles(accountId, clientId);
    }

    @Override
    @Transactional
    public Boolean delById(Integer roleId) {
        // 删除角色关联的菜单
        sysRelationService.delRelationFromId(roleId, SysRelationEnum.ROLE_MENU.getTbName());
        // 删除角色关联的用户
        sysRelationService.delRelationToId(roleId, SysRelationEnum.ACCOUNT_ROLE.getTbName());
        return removeById(roleId);
    }

    @Override
    public Boolean permRoleMenus(RoleMenuDto dto) {
        sysRelationService.editRelation(dto.getRoleId(), dto.getMenuIds(), SysRelationEnum.ROLE_MENU.getTbName());
        return Boolean.TRUE;
    }

    @Override
    public List<Map<String, Object>> roleGroup() {
        Map<String, List<Role>> groups = list().stream().collect(Collectors.groupingBy(Role::getClientId));
        List<Map<String, Object>> result = new ArrayList<>();
        for (String key : groups.keySet()) {
            ClientEnum clientEnum = ClientEnum.valueOf(key);
            Map<String, Object> map = new HashMap<>();
            List<Role> roles = groups.get(key);
            List<Map<String, Object>> options = roles.stream().map(role -> {
                Map<String, Object> option = new HashMap<>();
                option.put("value", role.getRoleId());
                option.put("label", role.getRoleName());
                return option;
            }).collect(Collectors.toList());
            map.put("label", clientEnum.getClientName());
            map.put("options", options);
            result.add(map);
        }
        return result;
    }
}
